﻿function getUrlVars() {
    var vars = [],
        hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
//接下来就是获取指定参数的值了，代码如下。
var roomid = getUrlVars()["roomid"];
var userids = getUrlVars()["userids"];
var orderid = getUrlVars()["orderid"];
//alert("roomid:" + roomid + "userids:" + userids + "orderid:" + orderid);

$(document).ready(function () {
    var keyid = $("#mainkeyid").html();
    console.log("服务表keyid是:" + keyid);
    //ajax加载主order表
    $.ajax({
        url: '/MJOrder/ashx/MJOrderHandler.ashx',
        type: 'POST', //GET
        async: true,    //或false,是否异步
        data: {
            "filter": "{\"groupOp\": \"AND\",\"rules\":[{\"field\":\"KeyId\",\"op\":\"eq\",\"data\":\"" + keyid + "\" }],\"groups\":[]}"
        },
        timeout: 5000,    //超时时间
        dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        beforeSend: function (xhr) {
            console.log(xhr)
            console.log('发送前')
        },
        success: function (data, textStatus, jqXHR) {
            console.log(data)
            console.log(textStatus)
            console.log(jqXHR)
            //$("#form1").populateForm(data.rows[0]);//将json数据回填到表单
            $('#form1').form('load', data.rows[0]);	// 这是EasyUI form load方法
            console.log("返回的Json数据：" + JSON.stringify(data.rows[0]));
            $("#total").numberbox('setValue', 0);
            $(".shifu").numberbox('setValue', 0);
            //alert(data.rows[0].total);
            console.log("回填数据:" + data);
        },
        error: function (xhr, textStatus) {
            console.log('错误')
            console.log(xhr)
            console.log(textStatus)
        },
        complete: function () {
            console.log('结束')
        }
    })


    //alert(document.body.clientHeight);
    //autoResize({ dataGrid: '#list', gridType: 'datagrid', width:0, height: 0 });
    $('#list').datagrid({
        url: '/MJOrderDetail/ashx/MJOrderDetailHandler.ashx?filter={"groupOp":"AND","rules":[{"field":"MJOrderid","op":"eq","data":"' + keyid + '"}],"groups":[]}&json={"action":"tui"}',
        singleSelect: true,//只能选择一行
        width: 1000,
        height: 400,
        toolbar: [{
            iconCls: 'icon-save',
            text: '保存',
            handler: function () {
                jisuan();//表单计算
            }
        }, {
            //徐总说先收费，后退费，这里隐藏新增收费项核算更清晰
            //iconCls: 'icon-add',
            //text: '新增收费项目',
            //handler: function () {
            //    $('#list').datagrid('appendRow', { type: '新增', KeyId: 0, MJOrderid: 0, serviceName: '', sprice: 0, newsprice: 0, num: 1, newnum: 1, allprice: 0, newallprice: 0, add_time: new Date().Format("yyyy-MM-dd"), exp_time: new Date().Format("yyyy-MM-dd"), tuiserviceName: '', tuiserviceId: 0, tuimoney: 0, tuinote: '无', note: '', dep: '', depid: 0, });
            //    var editIndex = $("#list").datagrid("getRows").length - 1;
            //    addedit(editIndex);
            //    console.log("添加编辑器完成");

            //    console.log("正在编辑的行索引：" + editIndex);


            //}

        }, {
            iconCls: 'icon-application',
            text: '重置表单',
            handler: function () {
                $('#list').datagrid('reload');
            }

        }],
        rowStyler: function (index, row) {
            //格式化行 这里也只用来做参考
            if (row.KeyId == 0) {//新增行，直接就返回颜色
                return 'background-color:#6293BB;color:#fff;';
            }
            if (row.KeyId > 0) {//如果是原始数据，改过的也要变颜色
                if (row.newsprice > 0) {
                    return 'background-color:#6293BB;color:#fff;';
                }
            }
        },
        rownumbers: true, //行号
        columns: [[

            {
                title: '类型', field: 'type', editor: {
                    type: 'textbox', options: {
                        readonly: true,
                    }
                }, formatter: function (value, row, index) {
                    if (row.KeyId > 0) {
                        if (row.newsprice > 0) {
                            return '续费';

                        } else {
                            return '原始';

                        }

                    } else {
                        return '新增';

                    }
                }
            },
            { title: '系统编号', field: 'KeyId', sortable: true, width: '', hidden: true, editor: { type: 'numberspinner', options: { required: false, validType: '', missingMessage: '' } } },
            { title: '订单ID', field: 'MJOrderid', sortable: true, width: '', hidden: true, editor: { type: 'numberspinner', options: { required: false, validType: '', missingMessage: '' } } },
            {
                title: '项目(品名)', field: 'serviceName', sortable: true, width: '100', editor: {
                    type: 'combogrid', options: {
                        required: true, panelWidth: 150, validType: 'length[1,1000]', url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJaccountingSubjects&field=subjectType&q=收入', columns: [[
                            { field: 'KeyId', title: 'ID', width: 20, hidden: false },
                            { field: 'subjectType', title: '类型', width: 30, hidden: false },
                            { field: 'subjectName', title: '项目', width: 100 },
                            { field: 'note', title: '备注', hidden: true, width: 100 },
                        ]], textField: 'subjectName', idField: 'subjectName', missingMessage: '服务名称不能为空！'

                    }
                }
            },
            { title: '项目ID', field: 'serviceId', sortable: true, width: '', hidden: true, editor: { type: 'textbox', options: { required: true, validType: 'number', missingMessage: '请输入数字' } } },

            { title: '总价', field: 'allprice', sortable: true, width: '', hidden: true, editor: { type: 'numberbox', options: { required: true, validType: 'money', readonly: true, missingMessage: '请输入正确的金额' } } },
            {
                title: '总价', field: 'newallprice', formatter: function (value, row, index) {
                    return row.allprice;
                    //if (value == undefined) {
                    //    //return 0;
                    //    return row.allprice;
                    //} else {
                    //    return value;
                    //}
                }, sortable: true, width: '', hidden: true, editor: { type: 'numberbox', options: { required: true, precision: 2, validType: 'money', value: 0, readonly: true, missingMessage: '请输入正确的金额' } }
            },
            {
                title: '开始时间', field: 'add_time', formatter: function (value, row, index) {
                    return new Date(value).Format("yyyy-MM-dd");
                }, sortable: true, width: '90', hidden: true, editor: { type: 'datebox', options: { required: true, validType: 'date', missingMessage: '请输入合法的日期' } }
            },
            {
                title: '到期时间', formatter: function (value, row, index) {
                    return new Date(value).Format("yyyy-MM-dd");
                }, field: 'exp_time', sortable: true, width: '90', hidden: true, editor: { type: 'datebox', options: { required: true, validType: 'date', missingMessage: '请输入合法的日期' } }
            },
            { title: '退费科目', field: 'tuiserviceName', width: '90' },
            { title: '退费科目ID', field: 'tuiserviceId', width: '90', hidden: true },
            { title: '单价', field: 'sprice', sortable: true, width: '', hidden: false, editor: { type: 'numberbox', options: { required: true, validType: 'number', missingMessage: '请输入数字' } } },
            {
                title: '单价', field: 'newsprice', formatter: function (value, row, index) {
                    //alert(value);
                    return row.sprice;
                    //if (value == undefined) {
                    //    //return 0;
                    //    return row.sprice;
                    //} else {
                    //    //return value;
                    //    return row.sprice;
                    //}
                }, sortable: true, width: '', hidden: true, editor: {
                    type: 'numberbox',
                    precision: 2, options: { required: true, validType: 'moneyAll', missingMessage: '请输入单价' }
                }
            },
            {
                title: '数量', field: 'num',


                sortable: true, width: '', hidden: false, editor: {
                    type: 'numberspinner', options: {
                        required: true, validType: 'number',
                        missingMessage: '请输入数字',

                    }
                }
            },
            {
                title: '数量', field: 'newnum', formatter: function (value, row, index) {
                    //alert(value);
                    return row.num;
                    //if (value == undefined) {
                    //    //return 0;
                    //    return row.num;
                    //} else {
                    //    return value;
                    //}
                }, sortable: true, width: '', hidden: true, editor: {
                    type: 'numberspinner', options: {
                        required: true, validType: 'number',



                        missingMessage: '请输入数字'
                    }
                }
            },
            {
                title: '退费金额', field: 'tuimoney', width: '90',
                //formatter: function (value, row, index) {
                //    //alert();
                //    if (value > 0) {
                //        return -value;
                //    } else {
                //        return value;
                //    }

                //},
                editor: {
                    type: 'numberbox', options: {
                        required: true, validType: 'moneyAll', value: 0, readonly: false, missingMessage: '请输入正确的金额',
                        precision: 2,
                        onChange: function (nv, ov) {
                            //alert(nv);
                            if (nv < 0) {

                            } else {
                                $(this).numberbox('setValue', -nv);
                            }

                        }

                    }
                }
            },
            {
                title: '备注', field: 'tuinote', hidden: true, width: '300',
                formatter: function (value, row, index) {
                    //alert();
                    return row.note;
                },
                editor: { type: 'textbox', options: { required: true, validType: '', missingMessage: '请输入备注' } }
            },
            {
                title: '备注', field: 'note', sortable: true, width: '300',
                //formatter: function (value, row, index) {
                //    //alert();
                //    return row.tuinote;
                //},
                hidden: false, editor: { type: 'textbox', options: { required: false, validType: '', missingMessage: '' } }
            },
            { title: '系统备注', field: 'setno', sortable: true, width: '100', hidden: false, editor: { type: 'combobox', options: { required: false, validType: '', missingMessage: '', readonly: true, disabled: true } } },
            { title: '部门名称', field: 'dep', sortable: true, width: '', hidden: true, editor: { type: 'combotree', options: { required: false, validType: '', missingMessage: '' } } },
            { title: '部门id', field: 'depid', sortable: true, width: '', hidden: true, editor: { type: 'numberspinner', options: { required: false, validType: '', missingMessage: '' } } },

        ]],
        onLoadSuccess: function (data) {//数据加载完后执行
            //alert(JSON.stringify(data));
            for (var i = 0; i < data.total; i++) {

                $('#list').datagrid('updateRow', {
                    index: i,
                    row: {
                        newallprice: 0,
                        newnum: 0,
                        newprice: 0,
                        type: '原始',
                        note: data.rows[i].tuinote

                    }
                });
                $("#list").datagrid('removeEditor', 'serviceName');//移除编辑器不允许编辑
                $("#list").datagrid("removeEditor", "newsprice");//
                $("#list").datagrid("removeEditor", "newnum");
                $("#list").datagrid("removeEditor", "newallprice");
                $("#list").datagrid("removeEditor", "type");
                $("#list").datagrid("removeEditor", "add_time");
                $("#list").datagrid("removeEditor", "exp_time");
                //$('#list').datagrid('beginEdit', i); //加载完成不加载编辑
            }
            //数据加载完后 给列赋初始值

        },
        onClickCell: function (index, field, value) { //双击可以修改
            console.log("点击表格" + field + "值：" + value + "索引:" + index);
            //alert(index);
            //alert($('#list').form('validate'));
            //$('#list').datagrid('beginEdit', index);
            //if (field == 'subject') {//如果当前选择的是科目名称
            //    var ed = $('#list').datagrid('getEditor', { index: index, field: 'subject' });//找到行editor
            //    $(ed.target).combobox({
            //        onSelect: function (rec) {//子节点选择时的动作
            //            var val = $(ed.target).combobox('getText');//得到combogrid的值
            //            var edb = $('#list').datagrid('getEditor', { index: index, field: 'subjectid' });//找到行editor 找到第一个列文本框编辑器
            //            $(edb.target).textbox('setText', val);//设置文本框
            //            var ft = $('#list').datagrid('getEditor', { index: index, field: 'ftype' });//得到收支类型
            //            $(ft.target).textbox('setValue', rec.subjectType);//设置收支类型

            //        }
            //    });//获得当前选择的值
            //}



        },
        onClickRow: function (index, row) {//单击行时
            console.log("单击行:" + index);
            $("#list").datagrid("acceptChanges");//接受值改变
            $('#list').datagrid('beginEdit', index);//开始编辑
            var cnumed = $('#list').datagrid('getEditor', { index: index, field: 'num' });
            var cspriceed = $("#list").datagrid("getEditor", { index: index, field: "sprice" });
            var ctuimoneyed = $("#list").datagrid("getEditor", { index: index, field: "tuimoney" });
            $(cnumed.target).numberspinner("setValue", row.num);
            var sp = $(cspriceed.target).numberbox("getValue");//单价
            //注意row.num是原始数量
            console.log("原始数量是：" + row.num);
            //根据数量得到总金额
            $(cnumed.target).numberspinner({
                value: row.num,
                onChange: function (nv, ov) {
                    console.log("新值是:" + nv);
                    console.log("数量乘单价是:"+sp*nv);
                    $(ctuimoneyed.target).numberbox("setValue",sp*nv);//数量乘以单价

                }
            });
            //根据单价得到总金额
            $(cspriceed.target).numberbox({
                onChange: function (nv, ov) {
                    console.log("新单价是:" + nv);
                    var num=$(cnumed.target).numberspinner("getValue");
                    $(ctuimoneyed.target).numberbox("setValue", num * nv);//数量乘以单价
                }
            });


        },
        //onAfterEdit: onEndEdit, //绑定datagrid结束编辑时触发事件
        onDblClickRow: function (index, row) {//双击row
            //alert("当前行："+index);
            return false;//取消双击编辑
            //alert(JSON.stringify(row));
            if (row.KeyId > 0) {//大于0 说明是原始数据 服务名称不需要编辑器
                var addtimeed = $('#list').datagrid('getEditor', { index: index, field: 'add_time' });
                var exptimeed = $('#list').datagrid('getEditor', { index: index, field: 'exp_time' });

                var newnumed = $('#list').datagrid('getEditor', { index: index, field: 'newnum' });
                $(newnumed.target).numberspinner('setValue', row.num);
                var newallpriceed = $('#list').datagrid('getEditor', { index: index, field: 'newallprice' });
                $(newallpriceed.target).numberbox('setValue', row.allprice);
                var newspriceed = $('#list').datagrid('getEditor', { index: index, field: 'newsprice' });
                $(newspriceed.target).numberbox('setValue', row.sprice);
                //$(addtimeed.target).datebox('setValue', row.add_time);//保持原始时间 设置添加时间为空
                //$(exptimeed.target).datebox('setValue', row.exp_time);
                //设置类型值
                var typeed = $('#list').datagrid('getEditor', { index: index, field: 'type' });
                $(typeed.target).textbox('setValue', '续费');



            } else {//说明是新增的行
                //$("#list").datagrid('addEditor', 'serviceName');//因为上面做了移除工作，这里要增加一个editor
                //添加编辑器
                addedit(index);

                $('#list').datagrid('beginEdit', index);
                //以下代码主要是用于行内编辑文本框做一些判断留着做一些参考
                var ed = $('#list').datagrid('getEditor', { index: index, field: 'serviceName' });//找到行editor
                $(ed.target).combogrid({
                    onSelect: function (rowIndex, rowData) {//子节点选择时的动作
                        var noteed = $('#list').datagrid('getEditor', { index: index, field: 'note' });//找到行editor 找到第一个列文本框编辑器
                        var sided = $('#list').datagrid('getEditor', { index: index, field: 'serviceId' });//科目ID
                        $(noteed.target).textbox('setValue', rowData.note);//设置备注文本框
                        $(sided.target).textbox('setValue', rowData.KeyId);//给隐藏科目ID设置值
                        //alert(rowData.KeyId);//自行车停车费
                        if (rowData.KeyId == 14) {
                            var seted = $('#list').datagrid('getEditor', { index: index, field: 'setno' });
                            $(seted.target).combobox({////启用编辑器
                                url: '/MJDevice_child/ashx/MJDevice_childHandler.ashx',
                                valueField: 'KeyId',
                                textField: 'dcname',
                                disabled: false,
                                readonly: false,
                                required: true,
                                missingMessage: '请选择电瓶车',
                                loadFilter: function (data) {//过滤显示
                                    return data.rows;
                                }
                            });
                            //alert("d");
                        } else {
                            var seted = $('#list').datagrid('getEditor', { index: index, field: 'setno' });
                            $(seted.target).combobox({////启用编辑器
                                disabled: true,
                                readonly: true
                            });
                        }

                    }
                });//获得当前选择的值




                // var deped = $('#list').datagrid('getEditor', { index: index, field: 'dep' });//得到部门ed
                // $(deped.target).combotree({
                //     required: true,
                //     validType: 'length[0,100]',
                //     url: '/sys/ashx/userhandler.ashx?json={"jsonEntity":"{}","action":"deps"}',
                //     textField: 'Title',
                //     onSelect: function (node) {
                //         var ed = $('#list').datagrid('getEditor', { index: index, field: 'depid' });
                //         $(ed.target).numberspinner('setValue', node.id); node.id = node.text;
                //     },
                //     missingMessage: ''
                // });
            }

            //新数量计算
            var newallpriceed = $('#list').datagrid('getEditor', { index: index, field: 'newallprice' });
            var newnumed = $('#list').datagrid('getEditor', { index: index, field: 'newnum' });//数量ed
            var newsled = $('#list').datagrid('getEditor', { index: index, field: 'newsprice' });//数量单价
            $(newsled.target).numberbox({//改变数量时动作
                min: 0,
                //precision: 2,
                onChange: function (newValue, oldValue) {
                    //alert("o" + oldValue + "n" + newValue);
                    //计算单价
                    var num = $(newnumed.target).numberspinner('getValue');
                    $(newallpriceed.target).numberbox('setValue', (num * newValue));
                    //alert(num);
                    //$("#total").numberbox('setValue', compute('allprice'));//设置总价

                }
            });
            $(newnumed.target).numberspinner({//数量改变时动作
                min: 1,
                max: 99999999,
                value: 1,
                onChange: function (newValue, oldValue) {
                    var sl = $(newsled.target).numberbox('getValue');
                    $(newallpriceed.target).numberbox('setValue', (sl * newValue));//总价=数量*单价
                    //alert(compute('allprice'));
                    //设置总价
                    //$("#total").numberbox('setValue', compute('allprice'));
                }
                //editable: false
            });

            //新数量计算


        }

    });
});

function addedit(index) {
    //alert("编辑索引:" + index);
    $("#list").datagrid('addEditor', [ //添加服务名称编辑器
        {
            field: 'serviceName', editor: {
                type: 'combogrid', options: {
                    required: true, panelWidth: 150, validType: 'length[1,1000]', url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJaccountingSubjects&field=subjectType&q=', columns: [[
                        { field: 'KeyId', title: 'ID', width: 20, hidden: false },
                        { field: 'subjectType', title: '类型', width: 30, hidden: false },
                        { field: 'subjectName', title: '项目', width: 100 },
                        { field: 'note', title: '备注', hidden: true, width: 100 },
                    ]], textField: 'subjectName', idField: 'subjectName', missingMessage: '服务名称不能为空！'

                }
            }
        },

        {
            field: 'sprice', editor: {
                type: 'numberbox', options: {
                    required: true, min: -999999,
                    precision: 2, validType: 'moneyAll', missingMessage: '请输入数字'
                }
            }
        },
        {
            field: 'newsprice', editor: {
                type: 'numberbox', options: {
                    required: true, min: -999999,
                    precision: 2, validType: 'moneyAll', missingMessage: '请输入数字'
                }
            }
        },
        { field: 'num', editor: { type: 'numberspinner', options: { required: true, validType: 'number', missingMessage: '请输入数字' } } },
        { field: 'newnum', editor: { type: 'numberspinner', options: { required: true, validType: 'number', missingMessage: '请输入数字' } } },
        { field: 'allprice', editor: { type: 'numberbox', options: { required: true, validType: 'moneyAll', value: 0, readonly: true, missingMessage: '请输入正确的金额' } } },
        { field: 'newallprice', editor: { type: 'numberbox', options: { required: true, validType: 'moneyAll', value: 0, readonly: true, missingMessage: '请输入正确的金额' } } },
        { field: 'add_time', editor: { type: 'datebox', options: { required: true, validType: 'date', missingMessage: '请输入合法的日期' } } },
        { field: 'exp_time', editor: { type: 'datebox', options: { required: true, validType: 'date', missingMessage: '请输入合法的日期' } } }
    ]);
    $('#list').datagrid('beginEdit', index);
    //
    //以下代码主要是用于行内编辑文本框做一些判断留着做一些参考
    var ed = $('#list').datagrid('getEditor', { index: index, field: 'serviceName' });//找到行editor
    var noteed = $('#list').datagrid('getEditor', { index: index, field: 'note' });//找到行editor 找到第一个列文本框编辑器
    var tuinoteed = $('#list').datagrid('getEditor', { index: index, field: 'tuinote' });
    var tuimoneyed = $('#list').datagrid('getEditor', { index: index, field: 'tuimoney' });
    $(tuimoneyed.target).numberbox({ readonly: true });
    var tuinoteValue = $(tuinoteed.target).textbox("getValue");
    //alert(tuinoteValue);
    $(noteed.target).textbox({
        onChange(newValue, oldValue) {
            $(tuinoteed.target).textbox('setValue', newValue);
        }
    });//重新给note//赋值
    var sided = $('#list').datagrid('getEditor', { index: index, field: 'serviceId' });//科目ID
    //alert("ed" + ed);
    $(ed.target).combogrid({
        onSelect: function (rowIndex, rowData) {//子节点选择时的动作
            $(noteed.target).textbox('setValue', rowData.note);//设置备注文本框
            $(sided.target).textbox('setValue', rowData.KeyId);//给隐藏科目ID设置值
            //alert(rowData.KeyId);//自行车停车费
            if (rowData.KeyId == 14) {
                var seted = $('#list').datagrid('getEditor', { index: index, field: 'setno' });
                $(seted.target).combobox({////启用编辑器
                    url: '/MJDevice_child/ashx/MJDevice_childHandler.ashx',
                    valueField: 'KeyId',
                    textField: 'dcname',
                    disabled: false,
                    readonly: false,
                    required: true,
                    missingMessage: '请选择电瓶车',
                    loadFilter: function (data) {//过滤显示
                        return data.rows;
                    }
                });
                //alert("d");
            } else {
                var seted = $('#list').datagrid('getEditor', { index: index, field: 'setno' });
                $(seted.target).combobox({////启用编辑器
                    disabled: true,
                    readonly: true
                });
            }

        }
    });//获得当前选择的值
    //新数量计算
    var numed = $('#list').datagrid('getEditor', { index: index, field: 'num' });
    var spriceed = $('#list').datagrid('getEditor', { index: index, field: 'sprice' });
    var allpriceed = $('#list').datagrid('getEditor', { index: index, field: 'allprice' });

    var newallpriceed = $('#list').datagrid('getEditor', { index: index, field: 'newallprice' });
    var newnumed = $('#list').datagrid('getEditor', { index: index, field: 'newnum' });//数量ed
    //单价这里定义错误一个名字
    var newsled = $('#list').datagrid('getEditor', { index: index, field: 'newsprice' });//单价
    $(newsled.target).numberbox({//改变数量时动作
        //min: 0,
        precision: 2,
        onChange: function (newValue, oldValue) {
            //alert("o" + oldValue + "n" + newValue);
            //计算单价
            var num = $(newnumed.target).numberspinner('getValue');
            $(numed.target).numberspinner('setValue', num);
            $(spriceed.target).numberbox('setValue', newValue);
            $(allpriceed.target).numberbox('setValue', (num * newValue));
            $(newallpriceed.target).numberbox('setValue', (num * newValue));
            //alert(num);
            //$("#total").numberbox('setValue', compute('allprice'));//设置总价

        }
    });
    $(newnumed.target).numberspinner({//数量改变时动作
        min: 1,
        max: 99999999,
        value: 1,
        onChange: function (newValue, oldValue) {
            var sl = $(newsled.target).numberbox('getValue');
            $(newallpriceed.target).numberbox('setValue', (sl * newValue));//总价=数量*单价
            //alert(compute('allprice'));
            //设置总价
            //$("#total").numberbox('setValue', compute('allprice'));
        }
        //editable: false
    });

    //新数量计算

}


//扩展datagrid:动态添加删除editor
$.extend($.fn.datagrid.methods, {
    addEditor: function (jq, param) {
        if (param instanceof Array) {
            $.each(param, function (index, item) {
                var e = $(jq).datagrid('getColumnOption', item.field);
                e.editor = item.editor;
            });
        } else {
            var e = $(jq).datagrid('getColumnOption', param.field);
            e.editor = param.editor;
        }
    },
    removeEditor: function (jq, param) {
        if (param instanceof Array) {
            $.each(param, function (index, item) {
                var e = $(jq).datagrid('getColumnOption', item);
                e.editor = {};
            });
        } else {
            var e = $(jq).datagrid('getColumnOption', param);
            e.editor = {};
        }
    }
});


// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//调用： 

//var time1 = new Date().Format("yyyy-MM-dd");
//var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss"); 

/*
*  datagrid 获取正在编辑状态的行，使用如下：
*  $('#id').datagrid('getEditingRowIndexs'); //获取当前datagrid中在编辑状态的行编号列表
*/
$.extend($.fn.datagrid.methods, {
    getEditingRowIndexs: function (jq) {
        var rows = $.data(jq[0], "datagrid").panel.find('.datagrid-row-editing');
        var indexs = [];
        rows.each(function (i, row) {
            var index = row.sectionRowIndex;
            if (indexs.indexOf(index) == -1) {
                indexs.push(index);
            }
        });
        return indexs;
    }
});


//经手人
$("#contactid").combogrid({
    panelWidth: 350,
    required: true,
    //value:'fullname',   
    idField: 'KeyId',
    editable: false,
    textField: 'TrueName',
    url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=Sys_Users&field=TrueName',
    columns: [[
        { field: 'TrueName', title: '姓名', width: 60 },
        { field: 'KeyId', title: 'KeyId', width: 100 }
    ]],
    onSelect: function (rowIndex, rowData) {
        $("#contactid").val(rowData.KeyId);//给经手人设置ID
        $("#contact").val(rowData.TrueName);//经手人
        //alert(rowData.TrueName);
    }
});

//表单计算
function jisuan() {
    var isValid = $("#form1").form('validate');//验证表单是否符合验证格式
    if (isValid) {
        //alert("p");
    } else {
        $.messager.alert('提醒', '表格没有填写完整');
        return false;//返回false 程序不执行
    }



    //asp.net 自动生成了一个form1 所以这里验证表单时有个#form1
    $('#list').datagrid('acceptChanges');
    var rows = $('#list').datagrid('getRows');//获取当前的数据行
    //alert(JSON.stringify(rows));
    var fzc = 0;//统计房租出现次数
    var total = 0;//计算sumMoney的总和
    var tuimoneyall = 0;//计算退还金额总和
    for (var i = 0; i < rows.length; i++) {
        if (rows[i]['serviceId'] == 3) {
            fzc = fzc + 1;
        }
        //alert(rows[i]['type']);
        //alert(rows[i]['newallprice']);
        total += parseFloat(rows[i]['newallprice']);
        tuimoneyall += parseFloat(rows[i]['tuimoney']);
    }
    if (fzc > 1) {
        $.messager.alert('提醒', '一个合同只允许出现一次房租！');
        return false;
    }
    //alert(total);

    total = total.toFixed(2);//保留小数点两位注意是字符哦 
    tuimoneyall = tuimoneyall.toFixed(2);
    console.log("退还金额总和" + tuimoneyall);
    total = Number(total) + Number(tuimoneyall);
    //alert(total);
    //$('#payment').textbox({ value: total });//加金额给实付金额
    $('#total').numberbox("setValue", total);//加金额给实付金额
    //实付金额手动来填写
    $('.shifu').eq(0).numberbox('setValue', total);//实付金额第一个给初始值
    //实付金额允许为0 因为有时候要给客户用
    //if ($(".shifu").eq(0).numberbox("getValue") == "0.00") {
    //    $.messager.alert('提醒', '实付金额不能为"0"!');
    //    return false;
    //}
    return true

}

//表单计算




//付款方式
function addpaytype() {
    var c = $("#paytypediv").children('li').length;
    if (c == 3) {//付款方式最多三个
        $.messager.alert('警告', '付款方式最多三个');
        return false;
    }
    var temp = '<li class="paytypeli"><input  name="account" class="account" value="" style="display: none;" />付款方式:<input  name="accountid" class="accountid" value="" />实付金额: <input type="text" name="shifu" class="easyui-numberbox shifu" value="0" style="width: 100px;" data-options="precision:2"></input><a  href="#"  class="easyui-linkbutton paytypea" data-options="iconCls:\'icon-cancel\'">删除</a></li> ';
    //alert(temp);
    $("#paytypediv").append(temp);
    initBank();//初始化银行
}

function initBank() {
    $(".easyui-linkbutton").linkbutton({});//初始化easyui按钮
    $(".shifu").numberbox({//初始化实付金额
        //min: 0,
        precision: 2,
        formatter: function (v) {
            //alert(v);
            if (v < 0) {
                return v;
            } else {
                return -v;
            }
        }
    });
    //银行
    $(".accountid").combobox({
        valueField: 'KeyId',//用中文名作为名称
        required: true,
        editable: false,
        validType: 'selectValueRequired',
        textField: 'accountName',
        url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJBankAccount&field=accountName',
        onSelect: function (rec) {
            $(this).prev('.account').val(rec.accountName);
            //$("#account").val(rec.accountName);//设置隐藏ID
        }
    });

    //alert("00");
    $(".paytypea").click(function (e) {
        $(this).closest("li").remove();
    });
}


//银行 打开时用一次性加载
$(".accountid").combobox({
    valueField: 'KeyId',//用中文名作为名称
    required: true,
    editable: false,
    validType: 'selectValueRequired',
    textField: 'accountName',
    url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJBankAccount&field=accountName',
    onSelect: function (rec) {
        $(this).prev('.account').val(rec.accountName);
        //$("#account").val(rec.accountName);//设置隐藏ID
    }
});

$("#submit").click(function () {
    tijiao();
});

function tijiao() {
    $('#form1').form('submit', {
        url: '/mjrooms/ashx/tuiroom.ashx',
        onSubmit: function (param) {
            var r = jisuan();//表单计算
            //alert("返回" + jisuan());
            if (r) {
                var rows = $('#list').datagrid('getRows');//获取当前的数据行
                param.main = $("#form1").serializeJSON();  //jquery方法把表单系列化成json后提交
                //以上用法参考https://github.com/macek/jquery-serialize-object
                param.detail = JSON.stringify(rows);//param  是EasyUI格式详细表序列化成json 
                //alert(param.main);
                //alert(param.detail);
                return r;
            } else {
                return r;
            }




            //return r;
            //rr = true;
            //return true;

        },
        success: function (d) {
            var d = eval('(' + d + ')');  // change the JSON string to javascript object    
            if (d.status == 1) {//返回1标识成功！返回0失败
                console.log("ajax成功" + d.msg);
                //如果成功，关闭当前窗口
                // 添加一个未选中状态的选项卡面板

                //var hasTab = top.$('#tabs').tabs('exists', '入住手续主表');

                //if (!hasTab) {
                //    top.$('#tabs').tabs('add', {
                //        title: '入住手续主表',
                //        content: createFrame('/MJOrder/MJOrder.aspx?navid=109'),
                //        //closable: (subtitle != onlyOpenTitle),
                //        icon: '/css/icon/32/note.png'
                //    });
                //} else {
                //    top.$('#tabs').tabs('select', '入住手续主表');
                //    var tab = top.$('#tabs').tabs('getSelected');  // 获取选择的面板
                //    //刷新当前面板
                //    tab.panel('refresh', '/MJOrder/MJOrder.aspx?navid=109');

                //    //closeTab('refresh'); //选择TAB时刷新页面
                //}
                //top.$('#tabs').tabs('close', '办理入住手续');//关闭办理入住手续
                //alert(api);
                //$.messager.alert('恭喜', d.msg);
                $.messager.confirm(d.msg, '要继续打印退租收据吗？', function (r) {
                    if (r) {
                        console.log("要打印，先打开打印窗口。然后关闭本窗口！");
                        //因为要操作父窗口所以用top.
                        var tab = top.$('#tabs').tabs('getSelected');//获取当前选中tabs  
                        var index = top.$('#tabs').tabs('getTabIndex', tab);//获取当前选中tabs的index  
                        top.$('#tabs').tabs('close', index);//关闭对应index的tabs
                        //PrintTZ(d.edNumber);
                        //top.closeTab('close'); //关闭窗口
                        //api.close();
                    } else {
                        console.log("不打印关闭窗口");
                        var tab = top.$('#tabs').tabs('getSelected');//获取当前选中tabs  
                        var index = top.$('#tabs').tabs('getTabIndex', tab);//获取当前选中tabs的index  
                        top.$('#tabs').tabs('close', index);//关闭对应index的tabs
                        //top.closeTab('close'); 
                        //api.close();//关闭窗口
                    }
                });




                //api.close();


                //location = '/MJOrder/MJOrder.aspx';//刷新本地网址
            } else {
                $.messager.alert('对不起!', d.msg);
                rr = false;
            }

            //
            //alert("成功动作");
            //$.messager.progress('close');	// 如果提交成功则隐藏进度条
        }
    });
}

//给公共变量赋值
$("#orderid").val(orderid);
$("#roomid").val(roomid);
$("#userids").val(userids);



$.fn.populateForm = function (data) {
    return this.each(function () {
        var formElem, name;
        if (data == null) { this.reset(); return; }
        for (var i = 0; i < this.length; i++) {
            formElem = this.elements[i];
            //checkbox的name可能是name[]数组形式
            name = (formElem.type == "checkbox") ? formElem.name.replace(/(.+)\[\]$/, "$1") : formElem.name;
            if (data[name] == undefined) continue;
            switch (formElem.type) {
                case "checkbox":
                    if (data[name] == "") {
                        formElem.checked = false;
                    } else {
                        //数组查找元素
                        if (data[name].indexOf(formElem.value) > -1) {
                            formElem.checked = true;
                        } else {
                            formElem.checked = false;
                        }
                    }
                    break;
                case "radio":
                    if (data[name] == "") {
                        formElem.checked = false;
                    } else if (formElem.value == data[name]) {
                        formElem.checked = true;
                    }
                    break;
                case "button": break;
                default: formElem.value = data[name];
            }
        }
    });
};


//编辑某个单元格
$.extend($.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var editIndex = undefined;
function endEditing() {
    if (editIndex == undefined) { return true }
    if ($('#list').datagrid('validateRow', editIndex)) {
        $('#list').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onClickCell(index, field) {
    if (endEditing()) {
        $('#list').datagrid('selectRow', index)
            .datagrid('editCell', { index: index, field: field });
        editIndex = index;
    }
}

//编辑某个单元格

function PrintXF(e) {
    alert(e);
    var dialog = $.dialog({
        title: "续费打印",
        content: 'url:' + '/mjprint/tuiroom.aspx?edNumber=' + e,
        min: false,
        max: false,
        lock: true,
        width: 850,
        height: 550
    });
    //top.closeTab('refresh');

}